package com.nine.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nine.common.entity.*;
import com.nine.system.mapper.UserInfoMapper;
import com.nine.system.service.LoginService;
import com.nine.common.tool.ResponseResult;
import org.apache.commons.codec.digest.Md5Crypt;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;

/**
 * @Description:
 * @ClassName: LoginServiceImpl
 * @Author: luodeng
 * @Date: 2023/6/7 9:57
 * @Version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private SendMessage sendMessage;

    @Override
    public ResponseResult login(User user) {

        String userName = user.getUserName();
        String password = user.getPassword();

        return checkLogin(password,userName);
    }

    @Override
    public ResponseResult logout() {
        StpUtil.logout();
        return ResponseResult.ok("退出成功");
    }


    @Override
    public ResponseResult resetPassword(String phoneNumber) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,phoneNumber);

        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if(userInfo == null){
            return ResponseResult.ok("该用户不存在");
        }

        int a = (int)(Math.random()*(9999-1000+1))+1000;//生成随机四位数
        String code = Integer.toString(a);
        userInfo.setCode(code);
        userInfoMapper.updateById(userInfo);

        String data = "{\"code\":\""+code+"\"}";

        try {
            sendMessage.DoSend(phoneNumber,data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.ok("验证码发送成功");
    }

    @Override
    public ResponseResult doVerify(String phoneNumber, String code,String newPassword) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,phoneNumber).eq(UserInfo::getCode,code);

        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if(userInfo == null){
            return ResponseResult.ok("手机号或者验证码错误");
        }

        //执行到这儿 说明手机号 code 都通过了验证  现在执行修改密码操作
        String s = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        userInfo.setPassword(s);
        userInfoMapper.updateById(userInfo);
        return  ResponseResult.ok("修改密码成功");
    }

    private ResponseResult checkLogin(String password,String userName){
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUsername,userName);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        if(userInfo == null){
            return ResponseResult.fail("账号或密码错误，请重试");
        }
        Long uid = userInfo.getUid();
        String encodePassword = DigestUtils.md5DigestAsHex(password.getBytes());

        if(!(userInfo.getPassword().equals(encodePassword))){
            return ResponseResult.fail("账号或密码错误，请重试");
        }
        ArrayList<String> permissions = userInfoMapper.getPermissions(uid);
        ArrayList<String> roles = userInfoMapper.getRoles(uid);
        LoginUser loginUser = new LoginUser();
        loginUser.setUserInfo(userInfo);
        loginUser.setPermissionCodeList(permissions);
        loginUser.setRoleCodeList(roles);

        StpUtil.login(userInfo.getUid());

        AuthUserHolder.setUserInfo(loginUser);

        LoginUser loginUser1 = AuthUserHolder.getLoginUser();
        System.out.println(loginUser1);

        ReturnLoginVO returnLoginVO = new ReturnLoginVO();
        returnLoginVO.setToken(loginUser1.getToken());
        returnLoginVO.setRole(roles.get(0));
        return ResponseResult.ok(returnLoginVO);

    }
}

